<template>
  <div class="h-full flex flex-col bg-gray-50 dark:bg-dark-950">
    <!-- Header -->
    <div class="bg-white dark:bg-dark-900 shadow-sm border-b border-gray-200 dark:border-dark-700 p-6 flex-shrink-0">
      <div class="flex items-center justify-between">
        <div>
          <h1 class="text-2xl font-bold text-gray-900 dark:text-gray-100">SQL日志管理</h1>
          <p class="text-sm text-gray-600 dark:text-gray-400 mt-1">AI中控SQL执行日志监控与审计</p>
        </div>
        <div class="flex items-center space-x-4">
          <!-- 统计卡片 -->
          <div class="grid grid-cols-4 gap-4">
            <div class="bg-blue-50 dark:bg-blue-900/20 p-3 rounded-lg">
              <div class="text-xs text-blue-600 dark:text-blue-400">总日志数</div>
              <div class="text-lg font-bold text-blue-700 dark:text-blue-300">{{ stats.total_logs }}</div>
            </div>
            <div class="bg-green-50 dark:bg-green-900/20 p-3 rounded-lg">
              <div class="text-xs text-green-600 dark:text-green-400">成功执行</div>
              <div class="text-lg font-bold text-green-700 dark:text-green-300">{{ stats.success_count }}</div>
            </div>
            <div class="bg-red-50 dark:bg-red-900/20 p-3 rounded-lg">
              <div class="text-xs text-red-600 dark:text-red-400">执行失败</div>
              <div class="text-lg font-bold text-red-700 dark:text-red-300">{{ stats.failed_count }}</div>
            </div>
            <div class="bg-yellow-50 dark:bg-yellow-900/20 p-3 rounded-lg">
              <div class="text-xs text-yellow-600 dark:text-yellow-400">高风险</div>
              <div class="text-lg font-bold text-yellow-700 dark:text-yellow-300">{{ stats.risk_distribution?.high || 0 }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Filters -->
    <div class="bg-white dark:bg-dark-900 p-4 border-b border-gray-200 dark:border-dark-700 flex-shrink-0">
      <div class="flex flex-wrap items-center gap-4">
        <!-- SQL类型筛选 -->
        <div class="flex items-center space-x-2">
          <label class="text-sm font-medium text-gray-700 dark:text-gray-300">SQL类型:</label>
          <select 
            v-model="filters.sql_type" 
            @change="loadData"
            class="form-select text-sm border-gray-300 dark:border-dark-600 dark:bg-dark-800 dark:text-gray-100 rounded-md"
          >
            <option value="">全部</option>
            <option value="SELECT">SELECT</option>
            <option value="INSERT">INSERT</option>
            <option value="UPDATE">UPDATE</option>
            <option value="DELETE">DELETE</option>
            <option value="CREATE">CREATE</option>
            <option value="ALTER">ALTER</option>
            <option value="DROP">DROP</option>
            <option value="OTHER">OTHER</option>
          </select>
        </div>

        <!-- 执行状态筛选 -->
        <div class="flex items-center space-x-2">
          <label class="text-sm font-medium text-gray-700 dark:text-gray-300">状态:</label>
          <select 
            v-model="filters.execution_status" 
            @change="loadData"
            class="form-select text-sm border-gray-300 dark:border-dark-600 dark:bg-dark-800 dark:text-gray-100 rounded-md"
          >
            <option value="">全部</option>
            <option value="pending">待执行</option>
            <option value="success">成功</option>
            <option value="failed">失败</option>
            <option value="cancelled">已取消</option>
          </select>
        </div>

        <!-- 风险等级筛选 -->
        <div class="flex items-center space-x-2">
          <label class="text-sm font-medium text-gray-700 dark:text-gray-300">风险等级:</label>
          <select 
            v-model="filters.risk_level" 
            @change="loadData"
            class="form-select text-sm border-gray-300 dark:border-dark-600 dark:bg-dark-800 dark:text-gray-100 rounded-md"
          >
            <option value="">全部</option>
            <option value="low">低风险</option>
            <option value="medium">中风险</option>
            <option value="high">高风险</option>
            <option value="critical">极高风险</option>
          </select>
        </div>

        <!-- 日期范围 -->
        <div class="flex items-center space-x-2">
          <label class="text-sm font-medium text-gray-700 dark:text-gray-300">开始日期:</label>
          <input 
            v-model="filters.start_date" 
            @change="loadData"
            type="date" 
            class="form-input text-sm border-gray-300 dark:border-dark-600 dark:bg-dark-800 dark:text-gray-100 rounded-md"
          >
        </div>
        <div class="flex items-center space-x-2">
          <label class="text-sm font-medium text-gray-700 dark:text-gray-300">结束日期:</label>
          <input 
            v-model="filters.end_date" 
            @change="loadData"
            type="date" 
            class="form-input text-sm border-gray-300 dark:border-dark-600 dark:bg-dark-800 dark:text-gray-100 rounded-md"
          >
        </div>
      </div>
    </div>

    <!-- Main Content -->
    <div class="flex-1 p-6 space-y-6 overflow-y-auto">
      <!-- Charts Row -->
      <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <!-- 执行状态分布图 -->
        <ChartComponent
          type="pie"
          title="执行状态分布"
          subtitle="SQL执行状态统计"
          :data="statusChartData"
          height="300px"
          :colors="['#10B981', '#F59E0B', '#EF4444', '#6B7280']"
          @refresh="loadData"
        />

        <!-- 风险等级分布图 -->
        <ChartComponent
          type="bar"
          title="风险等级分布"
          subtitle="SQL风险等级统计"
          :data="riskChartData"
          height="300px"
          :colors="['#10B981', '#F59E0B', '#EF4444', '#DC2626']"
          @refresh="loadData"
        />
      </div>

      <!-- 每日执行趋势图 -->
      <ChartComponent
        v-if="dailyStatsData.labels && dailyStatsData.labels.length > 0"
        type="line"
        title="每日执行趋势"
        subtitle="最近7天SQL执行统计"
        :data="dailyStatsData"
        height="300px"
        :colors="['#3B82F6', '#10B981', '#EF4444']"
        @refresh="loadData"
      />

      <!-- 普通表格 -->
      <div class="bg-white dark:bg-gray-800 rounded-lg shadow-sm overflow-hidden">
        <!-- 表格工具栏 -->
        <div class="px-4 py-3 border-b border-gray-200 dark:border-gray-700 flex items-center justify-between">
          <div class="flex items-center space-x-4">
            <button
              @click="loadData"
              class="inline-flex items-center px-3 py-2 border border-gray-300 dark:border-gray-600 shadow-sm text-sm font-medium rounded-md text-gray-700 dark:text-gray-200 bg-white dark:bg-gray-800 hover:bg-gray-50 dark:hover:bg-gray-700"
            >
              <ArrowPathIcon class="w-4 h-4 mr-2" />
              刷新
            </button>
          </div>
          <div class="flex items-center space-x-2">
            <div class="relative">
              <input
                v-model="searchText"
                @input="() => handleSearch(searchText)"
                type="text"
                placeholder="搜索..."
                class="pl-8 pr-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md text-sm bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100"
              >
              <MagnifyingGlassIcon class="absolute left-2 top-2.5 w-4 h-4 text-gray-400" />
            </div>
          </div>
        </div>

        <!-- 表格内容 -->
        <div class="overflow-x-auto max-h-96 overflow-y-auto">
          <table class="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
            <thead class="bg-gray-50 dark:bg-gray-700">
              <tr>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider cursor-pointer" @click="sortBy('id')">
                  ID
                  <ChevronUpDownIcon class="w-4 h-4 inline ml-1" />
                </th>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">用户</th>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">SQL语句</th>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">类型</th>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">目标表</th>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">状态</th>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">风险等级</th>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">执行时间(ms)</th>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider cursor-pointer" @click="sortBy('created_at')">
                  创建时间
                  <ChevronUpDownIcon class="w-4 h-4 inline ml-1" />
                </th>
                <th class="px-6 py-3 text-center text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">操作</th>
              </tr>
            </thead>
            <tbody class="bg-white dark:bg-gray-800 divide-y divide-gray-200 dark:divide-gray-700">
              <tr v-if="loading" class="bg-white dark:bg-gray-800">
                <td colspan="10" class="px-6 py-4 text-center text-gray-500 dark:text-gray-400">
                  <div class="flex items-center justify-center">
                    <div class="animate-spin rounded-full h-6 w-6 border-b-2 border-blue-600"></div>
                    <span class="ml-2">加载中...</span>
                  </div>
                </td>
              </tr>
              <tr v-else-if="logs.length === 0" class="bg-white dark:bg-gray-800">
                <td colspan="10" class="px-6 py-4 text-center text-gray-500 dark:text-gray-400">
                  暂无数据
                </td>
              </tr>
              <tr v-else v-for="log in logs" :key="log.id" class="bg-white dark:bg-gray-800 hover:bg-gray-50 dark:hover:bg-gray-700">
                <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900 dark:text-gray-100">
                  {{ log.id }}
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900 dark:text-gray-100">
                  {{ (log as any).user_display }}
                </td>
                <td class="px-6 py-4 text-sm text-gray-900 dark:text-gray-100 max-w-xs">
                  <div class="truncate" :title="log.sql_statement">
                    {{ log.sql_statement }}
                  </div>
                </td>
                <td class="px-6 py-4 whitespace-nowrap">
                  <span :class="getStatusClass(log.sql_type, 'sql_type')" class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium">
                    {{ getStatusLabel(log.sql_type, 'sql_type') }}
                  </span>
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900 dark:text-gray-100">
                  {{ log.target_table }}
                </td>
                <td class="px-6 py-4 whitespace-nowrap">
                  <span :class="getStatusClass(log.execution_status, 'execution_status')" class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium">
                    {{ getStatusLabel(log.execution_status, 'execution_status') }}
                  </span>
                </td>
                <td class="px-6 py-4 whitespace-nowrap">
                  <span :class="getStatusClass(log.risk_level, 'risk_level')" class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium">
                    {{ getStatusLabel(log.risk_level, 'risk_level') }}
                  </span>
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900 dark:text-gray-100">
                  {{ log.execution_time }}ms
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900 dark:text-gray-100">
                  {{ formatDateTime(log.created_at) }}
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-center text-sm font-medium">
                  <div class="flex items-center justify-center space-x-2">
                    <button
                      @click="viewDetail(log)"
                      class="text-blue-600 hover:text-blue-700 hover:bg-blue-50 dark:text-blue-400 dark:hover:text-blue-300 dark:hover:bg-blue-900/20 inline-flex items-center px-2 py-1 text-xs font-medium rounded transition-colors duration-200"
                    >
                      <EyeIcon class="w-3 h-3 mr-1" />
                      查看
                    </button>
                    <button
                      @click="approveLog(log, true)"
                      class="text-green-600 hover:text-green-700 hover:bg-green-50 dark:text-green-400 dark:hover:text-green-300 dark:hover:bg-green-900/20 inline-flex items-center px-2 py-1 text-xs font-medium rounded transition-colors duration-200"
                    >
                      <CheckIcon class="w-3 h-3 mr-1" />
                      通过
                    </button>
                    <button
                      @click="approveLog(log, false)"
                      class="text-red-600 hover:text-red-700 hover:bg-red-50 dark:text-red-400 dark:hover:text-red-300 dark:hover:bg-red-900/20 inline-flex items-center px-2 py-1 text-xs font-medium rounded transition-colors duration-200"
                    >
                      <XMarkIcon class="w-3 h-3 mr-1" />
                      拒绝
                    </button>
                  </div>
                </td>
              </tr>
            </tbody>
          </table>
        </div>

        <!-- 分页器 -->
        <div class="px-4 py-3 border-t border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800/50 flex items-center justify-between">
          <div class="flex items-center text-sm text-gray-700 dark:text-gray-300">
            显示第 {{ (pagination.page - 1) * pagination.limit + 1 }} 到 {{ Math.min(pagination.page * pagination.limit, pagination.total) }} 条，共 {{ pagination.total }} 条
          </div>
          <div class="flex items-center space-x-2">
            <button
              @click="handlePageChange({ currentPage: pagination.page - 1, pageSize: pagination.limit })"
              :disabled="pagination.page <= 1"
              class="px-3 py-1 text-sm border border-gray-300 dark:border-gray-600 rounded-md text-gray-700 dark:text-gray-200 bg-white dark:bg-gray-800 hover:bg-gray-50 dark:hover:bg-gray-700 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              上一页
            </button>
            <span class="px-3 py-1 text-sm text-gray-700 dark:text-gray-300">
              第 {{ pagination.page }} 页
            </span>
            <button
              @click="handlePageChange({ currentPage: pagination.page + 1, pageSize: pagination.limit })"
              :disabled="pagination.page * pagination.limit >= pagination.total"
              class="px-3 py-1 text-sm border border-gray-300 dark:border-gray-600 rounded-md text-gray-700 dark:text-gray-200 bg-white dark:bg-gray-800 hover:bg-gray-50 dark:hover:bg-gray-700 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              下一页
            </button>
          </div>
        </div>
      </div>
      
    </div>

    <!-- Detail Modal -->
    <div v-if="showDetailModal" class="fixed inset-0 z-50 overflow-y-auto">
      <div class="flex items-center justify-center min-h-screen px-4 pt-4 pb-20 text-center sm:block sm:p-0">
        <div class="fixed inset-0 transition-opacity bg-gray-500 bg-opacity-75 dark:bg-gray-900 dark:bg-opacity-75" @click="closeDetailModal"></div>

        <div class="inline-block w-full max-w-4xl p-6 my-8 overflow-hidden text-left align-middle transition-all transform bg-white dark:bg-dark-800 shadow-xl rounded-lg">
          <div class="flex items-center justify-between mb-4">
            <h3 class="text-lg font-medium text-gray-900 dark:text-gray-100">SQL日志详情</h3>
            <button @click="closeDetailModal" class="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300">
              <XMarkIcon class="w-6 h-6" />
            </button>
          </div>

          <div v-if="selectedLog" class="space-y-4">
            <!-- 基本信息 -->
            <div class="grid grid-cols-2 gap-4">
              <div>
                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300">日志ID</label>
                <p class="text-sm text-gray-900 dark:text-gray-100">{{ selectedLog.id }}</p>
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300">执行用户</label>
                <p class="text-sm text-gray-900 dark:text-gray-100">{{ selectedLog.user?.realName || selectedLog.user?.username || `用户${selectedLog.user_id}` }}</p>
              </div>
            </div>

            <!-- SQL语句 -->
            <div>
              <label class="block text-sm font-medium text-gray-700 dark:text-gray-300">SQL语句</label>
              <pre class="mt-2 p-4 bg-gray-100 dark:bg-gray-700 rounded-md text-sm font-mono overflow-x-auto">{{ selectedLog.sql_statement || '无' }}</pre>
            </div>

            <!-- AI响应 -->
            <div v-if="selectedLog.ai_response">
              <label class="block text-sm font-medium text-gray-700 dark:text-gray-300">AI响应</label>
              <div class="mt-2 p-4 bg-gray-100 dark:bg-gray-700 rounded-md text-sm" v-html="formatMarkdown(selectedLog.ai_response)"></div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { sqlLogAPI } from '@/api'
import type { SQLLog } from '@/types'
import { format } from 'date-fns'
import { zhCN } from 'date-fns/locale'
import ChartComponent from '@/components/ChartComponent.vue'
import { XMarkIcon, ArrowPathIcon, MagnifyingGlassIcon, EyeIcon, CheckIcon, ChevronUpDownIcon } from '@heroicons/vue/24/outline'

// Reactive state
const loading = ref(false)
const logs = ref<SQLLog[]>([])
const selectedLog = ref<SQLLog | null>(null)
const showDetailModal = ref(false)
const searchText = ref('')

// Pagination
const pagination = reactive({
  page: 1,
  limit: 20,
  total: 0
})

// Filters
const filters = reactive({
  sql_type: '',
  execution_status: '',
  risk_level: '',
  start_date: '',
  end_date: ''
})

// Stats
const stats = reactive({
  total_logs: 0,
  success_count: 0,
  failed_count: 0,
  risk_distribution: {} as Record<string, number>,
  daily_stats: [] as any[]
})

// 移除不再需要的paginationData

// Chart data
const statusChartData = computed(() => ({
  series: [{
    name: '执行状态',
    type: 'pie',
    radius: ['40%', '70%'],
    data: [
      { name: '成功', value: stats.success_count },
      { name: '待执行', value: stats.total_logs - stats.success_count - stats.failed_count },
      { name: '失败', value: stats.failed_count },
      { name: '其他', value: 0 }
    ].filter(item => item.value > 0)
  }]
}))

const riskChartData = computed(() => ({
  labels: ['低风险', '中风险', '高风险', '极高风险'],
  series: [{
    name: '风险等级',
    type: 'bar',
    data: [
      stats.risk_distribution?.low || 0,
      stats.risk_distribution?.medium || 0,
      stats.risk_distribution?.high || 0,
      stats.risk_distribution?.critical || 0
    ]
  }]
}))

const dailyStatsData = computed(() => {
  if (!stats.daily_stats || stats.daily_stats.length === 0) {
    return { labels: [], series: [] }
  }
  
  const labels = stats.daily_stats.map((item: any) => format(new Date(item.date), 'MM-dd'))
  
  return {
    labels,
    series: [
      {
        name: '总执行数',
        type: 'line',
        data: stats.daily_stats.map((item: any) => item.count),
        smooth: true
      },
      {
        name: '成功数',
        type: 'line',
        data: stats.daily_stats.map((item: any) => item.success),
        smooth: true
      },
      {
        name: '失败数',
        type: 'line',
        data: stats.daily_stats.map((item: any) => item.failed),
        smooth: true
      }
    ]
  }
})

// Methods
const loadData = async () => {
  loading.value = true
  try {
    const [logsResponse, statsResponse] = await Promise.all([
      sqlLogAPI.getSQLLogs({
        page: pagination.page,
        limit: pagination.limit,
        ...filters
      }),
      sqlLogAPI.getSQLLogStats(filters.start_date || filters.end_date ? {
        start_date: filters.start_date,
        end_date: filters.end_date
      } : undefined)
    ])

    if (logsResponse.success && logsResponse.data) {
      // 处理数据结构差异 - 后端返回的是 {list, pagination}，前端期望的是 {logs, total, page, limit}
      const data = logsResponse.data
      const logsList = data.list || []
      const paginationInfo = data.pagination || {}
      
      // 处理用户显示名称
      logs.value = logsList.map((log: any) => ({
        ...log,
        user_display: log.executor?.real_name || log.executor?.username || log.user?.realName || log.user?.username || `用户${log.user_id}`
      }))
      
      pagination.total = paginationInfo.total || 0
      pagination.page = paginationInfo.current || 1
      pagination.limit = paginationInfo.pageSize || 20
    }

    if (statsResponse.success && statsResponse.data) {
      // 处理统计数据结构差异
      const statsData = statsResponse.data
      Object.assign(stats, {
        total_logs: statsData.total || 0,
        success_count: statsData.statusStats?.success || 0,
        failed_count: statsData.statusStats?.failed || 0,
        risk_distribution: statsData.riskLevelStats || {},
        daily_stats: (statsData as any).daily_stats || []
      })
    }
  } catch (error) {
    console.error('加载SQL日志失败:', error)
  } finally {
    loading.value = false
  }
}

const handleSearch = (searchText: string) => {
  // 实现搜索逻辑
  console.log('搜索:', searchText)
}

const handlePageChange = (params: any) => {
  pagination.page = params.currentPage
  pagination.limit = params.pageSize
  loadData()
}

// 移除不再需要的handleTableAction方法

const viewDetail = (log: SQLLog) => {
  selectedLog.value = log
  showDetailModal.value = true
}

const closeDetailModal = () => {
  showDetailModal.value = false
  selectedLog.value = null
}

const approveLog = async (log: SQLLog, approved: boolean) => {
  try {
    const response = await sqlLogAPI.approveSQLLog(log.id, { approved })
    if (response.success) {
      loadData()
    }
  } catch (error) {
    console.error('审批SQL日志失败:', error)
  }
}

const formatMarkdown = (text: string) => {
  return text
    .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
    .replace(/\*(.*?)\*/g, '<em>$1</em>')
    .replace(/`(.*?)`/g, '<code class="bg-gray-200 dark:bg-gray-700 px-1 rounded">$1</code>')
    .replace(/\n/g, '<br>')
}

const formatDateTime = (dateStr: string | Date) => {
  try {
    const date = typeof dateStr === 'string' ? new Date(dateStr) : dateStr
    return format(date, 'yyyy-MM-dd HH:mm:ss', { locale: zhCN })
  } catch {
    return dateStr
  }
}

const getStatusClass = (value: any, type: string) => {
  const colorMap: Record<string, Record<string, string>> = {
    sql_type: {
      SELECT: 'bg-blue-100 text-blue-800 dark:bg-blue-900/20 dark:text-blue-300',
      INSERT: 'bg-green-100 text-green-800 dark:bg-green-900/20 dark:text-green-300',
      UPDATE: 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/20 dark:text-yellow-300',
      DELETE: 'bg-red-100 text-red-800 dark:bg-red-900/20 dark:text-red-300',
      CREATE: 'bg-blue-100 text-blue-800 dark:bg-blue-900/20 dark:text-blue-300',
      ALTER: 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/20 dark:text-yellow-300',
      DROP: 'bg-red-100 text-red-800 dark:bg-red-900/20 dark:text-red-300',
      OTHER: 'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300'
    },
    execution_status: {
      pending: 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/20 dark:text-yellow-300',
      success: 'bg-green-100 text-green-800 dark:bg-green-900/20 dark:text-green-300',
      failed: 'bg-red-100 text-red-800 dark:bg-red-900/20 dark:text-red-300',
      cancelled: 'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300'
    },
    risk_level: {
      low: 'bg-green-100 text-green-800 dark:bg-green-900/20 dark:text-green-300',
      medium: 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/20 dark:text-yellow-300',
      high: 'bg-red-100 text-red-800 dark:bg-red-900/20 dark:text-red-300',
      critical: 'bg-red-100 text-red-800 dark:bg-red-900/20 dark:text-red-300'
    }
  }
  return colorMap[type]?.[value] || 'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300'
}

const getStatusLabel = (value: any, type: string) => {
  const labelMap: Record<string, Record<string, string>> = {
    sql_type: {
      SELECT: 'SELECT',
      INSERT: 'INSERT',
      UPDATE: 'UPDATE',
      DELETE: 'DELETE',
      CREATE: 'CREATE',
      ALTER: 'ALTER',
      DROP: 'DROP',
      OTHER: 'OTHER'
    },
    execution_status: {
      pending: '待执行',
      success: '成功',
      failed: '失败',
      cancelled: '已取消'
    },
    risk_level: {
      low: '低风险',
      medium: '中风险',
      high: '高风险',
      critical: '极高风险'
    }
  }
  return labelMap[type]?.[value] || value
}

const sortBy = (field: string) => {
  // 简单的排序逻辑，可以根据需要扩展
  console.log('排序字段:', field)
}

// Lifecycle
onMounted(() => {
  loadData()
})
</script>

<style scoped>
/* 自定义样式 */
</style>
